import axios from 'axios';

export async function getAccessToken(corpid: string, corpsecret: string): Promise<string> {
    const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpid}&corpsecret=${corpsecret}`;
    try {
        const response = await axios.get(url);

        if (response.status === 200) {
            const data = response.data;
            if (data.errcode === 0) {
                return data.access_token;
            } else {
                return `Error: ${data.errcode}, ${data.errmsg}`;
            }
        } else {
            return `HTTP Error: ${response.status}`;
        }
    } catch (error) {
        return `Request failed: ${error}`;
    }
}


export async function createWechatWorkspace(accessToken: string, spaceName: string, authInfo?: any, spaceSubType: number = 0) {
    const url = `https://qyapi.weixin.qq.com/cgi-bin/wedrive/space_create?access_token=${accessToken}`;

    const payload: any = {
        space_name: spaceName,
        space_sub_type: spaceSubType
    };

    if (authInfo) {
        payload.auth_info = authInfo;
    }

    const headers = {
        'Content-Type': 'application/json'
    };

    try {
        const response = await axios.post(url, payload, { headers });
        return response.data;
    } catch (error) {
        console.error('Error creating workspace:', error);
        throw error;
    }
}


export async function createWechatWorkDoc(accessToken: string, spaceid: string, fatherid: string, docType: number, docName: string, adminUsers: string[]) {
    const url = `https://qyapi.weixin.qq.com/cgi-bin/wedoc/create_doc?access_token=${accessToken}`;

    const headers = {
        'Content-Type': 'application/json'
    };

    const payload = {
        spaceid: spaceid,
        fatherid: fatherid,
        doc_type: docType,
        doc_name: docName,
        admin_users: adminUsers
    };

    try {
        const response = await axios.post(url, payload, { headers });
        if (response.status === 200) {
            return response.data;
        } else {
            console.error(`Error: ${response.status}`);
            console.error(`Response: ${response.statusText}`);
            return null;
        }
    } catch (error) {
        console.error('Error creating document:', error);
        throw error;
    }
}


export async function addRecords(accessToken: string, docid: string, sheetId: string, records: any[]) {
    const url = `https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/add_records?access_token=${accessToken}`;

    const payload = {
        docid: docid,
        sheet_id: sheetId,
        key_type: 'CELL_VALUE_KEY_TYPE_FIELD_TITLE',
        records: records
    };

    const headers = {
        'Content-Type': 'application/json'
    };

    try {
        const response = await axios.post(url, payload, { headers });
        return response.data;
    } catch (error) {
        console.error('Error adding records:', error);
        throw error;
    }
}

interface Properties {
    title?: string;
    index?: number;
}

interface AddSheetResponse {
    errcode: number;
    errmsg: string;
    properties: {
        title: string;
        index: number;
        sheet_id: string;
    };
}

export async function addSubSheet(accessToken: string, docid: string, properties: Properties): Promise<AddSheetResponse> {
    const url = `https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/add_sheet?access_token=${accessToken}`;

    const payload = {
        docid: docid,
        properties: properties
    };

    const headers = {
        'Content-Type': 'application/json'
    };

    try {
        const response = await axios.post(url, payload, { headers });
        return response.data as AddSheetResponse;
    } catch (error) {
        console.error('Error adding sub sheet:', error);
        throw error;
    }
}


interface Field {
    field_title: string;
    field_type: string;
}

interface AddFieldsResponse {
    errcode: number;
    errmsg: string;
    fields: {
        field_id: string;
        field_title: string;
        field_type: string;
    }[];
}

export async function addFields(accessToken: string, docid: string, sheetId: string, fields: Field[]): Promise<AddFieldsResponse> {
    const url = `https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/add_fields?access_token=${accessToken}`;

    const payload = {
        docid: docid,
        sheet_id: sheetId,
        fields: fields
    };

    const headers = {
        'Content-Type': 'application/json'
    };

    try {
        const response = await axios.post(url, payload, { headers });
        return response.data as AddFieldsResponse;
    } catch (error) {
        console.error('Error adding fields:', error);
        throw error;
    }
}